package com.lgh.demo.viewModel;

import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.text.Html;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.Toast;
import com.lgh.demo.MyApplication;
import com.lgh.demo.R;
import com.lgh.demo.activity.DetailsActivity;
import com.lgh.demo.activity.SubmitActivity;
import com.lgh.demo.bean.BeanFoodInfo;
import com.lgh.demo.databinding.ActivityDetailsBinding;
import com.lgh.demo.databinding.ItemFoodBinding;
import com.lgh.demo.util.ActivityUtils;
import com.lgh.demo.util.DensityHelper;
import com.lgh.demo.util.ViewUtil;
import com.lgh.demo.util.WMConstantUtil;
import com.lgh.demo.view.BorderEffect;
import com.lgh.demo.view.BorderView;
import com.sankuai.waimai.opensdk.MTWMApi;
import com.sankuai.waimai.opensdk.callback.LoadDataListener;
import com.sankuai.waimai.opensdk.request.model.PayLoad;
import com.sankuai.waimai.opensdk.response.model.food.FoodInfo;
import com.sankuai.waimai.opensdk.response.model.preview.PreviewOrder;
import java.util.ArrayList;
import java.util.List;

public class VMSellersDetail implements BorderEffect.FocusListener {

    private DetailsActivity detailsActivity;
    private ActivityDetailsBinding detailsBinding;
    private long mPoiId;
    private FoodInfo foodInfo;
    private BorderView borderView;
    private int selectTypeIndex = 0;
    private View selectView;
    private PreviewOrder mPreviewOrder;

    public VMSellersDetail(DetailsActivity detailsActivity, ActivityDetailsBinding detailsBinding, long mPoiId) {
        this.detailsActivity = detailsActivity;
        this.detailsBinding = detailsBinding;
        this.mPoiId = mPoiId;

        getData();
    }

    private void initBorderView() {
        borderView = new BorderView(detailsActivity);
        borderView.setBackgroundResource(R.drawable.focus_default);
        borderView.attachTo(detailsBinding.llFoodChoice);
        borderView.attachTo(detailsBinding.llMenus);
        borderView.attachTo(detailsBinding.rlMainContent);
        borderView.getEffect().addOnFocusChanged(this);
    }

    private void getData() {
        MTWMApi.getPoiFood(MyApplication.longtitude, MyApplication.latitude, MyApplication.mPoiId, new LoadDataListener<FoodInfo>() {
            @Override
            public void onSuccess(FoodInfo data) {
                foodInfo = data;
                detailsBinding.setPoiBaseInfo(data.getPoiInfo());
                addLeftType();
                Log.d("getPoiFood", data.toString());
            }

            @Override
            public void onError(String errorMsg) {
                Toast.makeText(detailsActivity, "失败了。原因：" + errorMsg, Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void addLeftType() {
        for (int i = 0; i < foodInfo.getFoodSpuTags().size(); i++) {
            CheckBox itemFoodype = (CheckBox) View.inflate(detailsActivity, R.layout.item_food_type, null);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                    (int) DensityHelper.pt2px(detailsActivity, 60));
            detailsBinding.llMenus.addView(itemFoodype, params);
            itemFoodype.setText(foodInfo.getFoodSpuTags().get(i).getName());
        }

        if (foodInfo.getFoodSpuTags().size() > 0) {
            addRightContent();
        }

        initBorderView();
    }

    private void addRightContent() {
        detailsBinding.llFoodChoice.removeAllViews();
        for (int i = 0; i < foodInfo.getFoodSpuTags().get(selectTypeIndex).getSpus().size(); i++) {
            ItemFoodBinding itemFoodBinding = DataBindingUtil.inflate(LayoutInflater.from(detailsActivity), R.layout.item_food,
                    null, false);
            View view = itemFoodBinding.getRoot();
            FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                    (int) DensityHelper.pt2px(detailsActivity, 141));
            detailsBinding.llFoodChoice.addView(view, params);

            BeanFoodInfo beanFoodInfo = new BeanFoodInfo(foodInfo.getFoodSpuTags().get(selectTypeIndex).getSpus().get(i));
            itemFoodBinding.setBeanFoodInfo(beanFoodInfo);
            itemFoodBinding.setVmSellersDetail(this);
            view.setTag(itemFoodBinding);
        }
    }

    public void clickFood(View view) {

    }

    public void selectOk(View view) {
        if (hadSelectGood()){
            loadPreviewOrder();
        }else{
            Toast.makeText(detailsActivity,"请先选择菜品",Toast.LENGTH_LONG).show();
        }
    }

    private boolean hadSelectGood(){
        for (int i = 0; i < detailsBinding.llFoodChoice.getChildCount(); i++) {
            ItemFoodBinding itemFoodBinding = (ItemFoodBinding) detailsBinding.llFoodChoice.getChildAt(i).getTag();
            int count = itemFoodBinding.getBeanFoodInfo().getSelectCount();
            if (count>0){
                return true;
            }
        }
        return false;
    }

    public void loadPreviewOrder() {
        PayLoad previewPayload = createPreviewLoad();
        MTWMApi.getPreveiewOrder(previewPayload, new LoadDataListener<PreviewOrder>() {
            @Override
            public void onSuccess(PreviewOrder data) {
                mPreviewOrder = data;
                if (mPreviewOrder != null) {
                    if (mPreviewOrder.getCode() == 0) {
                        Intent intent = new Intent(detailsActivity, SubmitActivity.class);
                        intent.putExtra(WMConstantUtil.KEY_Preview_Order, mPreviewOrder);
                        intent.putExtra(WMConstantUtil.KEY_POI_IMG, detailsBinding.getPoiBaseInfo().getPicUrl());
                        ActivityUtils.gotoActivityWithIntent(detailsActivity, intent);
                    } else {
                        handleErrorCode(mPreviewOrder.getCode());
                    }
                }
            }

            @Override
            public void onError(String errorMsg) {
                Toast.makeText(detailsActivity, errorMsg, Toast.LENGTH_LONG).show();
            }
        });
    }

    /**
     * 异常code处理
     * 订单状态码 0:成功 1:失败 2:商家不可买 3:菜品不可买 4:不在配送时间内 5:菜品未达起送金额 15:未达到最小菜品起送份数 20:缺少必选菜品 21:菜品信息为空 26:商家不支持此配送类型 其他:系统维护,稍后重试
     * @param code
     */
    private void handleErrorCode(int code) {
        if (code == 0) {
            return;
        }
        String errorMsg = "系统升级,稍后重试";
        switch (code) {
            case 1:
                errorMsg = "失败";
                break;
            case 2:
                errorMsg = "商家不可买";
                break;
            case 3:
                errorMsg = "菜品不可买";
                break;
            case 4:
                errorMsg = "不在配送时间内";
                break;
            case 5:
                errorMsg = "菜品未达起送金额";
                break;
            case 15:
                errorMsg = "未达到菜品最小起送份数";
                break;
            case 20:
                errorMsg = "缺少必选菜品";
                break;
            case 21:
                errorMsg = "菜品信息为空";
                break;
            case 26:
                errorMsg = "商家不支持此配送类型";
                break;
            default:
                errorMsg = "系统升级,稍后重试";
                break;
        }
        Toast.makeText(detailsActivity, errorMsg, Toast.LENGTH_LONG).show();
    }

    /**
     * 创建订单提交数据
     *
     * @return 返回一个完整的PayLoad对象
     */
    private PayLoad createPreviewLoad() {
        PayLoad payLoad = new PayLoad();
        payLoad.setSubmit(false);
        // begin ---- 以下信息为选填。
//        WMDemoUser localUser = WMDemoUserManager.getInstance().getUser();

//        payLoad.setUserPhone(localUser.getUserPhone());
//        PayLoad.WmOrderingUser user = new PayLoad.WmOrderingUser();
//        payLoad.setWmUserInfo(user);
//        user.setUserPhone(localUser.getUserPhone());
//        user.setUserName(localUser.getUserName());
//        user.setUserAddress(localUser.getAddress());
//        user.setUserCaution("少放辣");
//
//        user.setAddrLatitude(AppApplication.latitude);
//        user.setAddrLongtitude(AppApplication.longtitude);
        // end

        // 每一家店铺的商品信息，可以一次性下单多个商家的订单信息。
        PayLoad.WmOrderingList wmOrderingList = new PayLoad.WmOrderingList();
        payLoad.setWmOrderingList(wmOrderingList);
        wmOrderingList.setWmPoiId(MyApplication.mPoiId);//商家ID
        wmOrderingList.setDeliveryTime(0);//用户选择的送达时间 0为立即送出
        wmOrderingList.setPayType(2);//支付类型 1-餐到付款 2-在线支付
        List<PayLoad.FoodItem> foodItems = new ArrayList<>();//某一家店铺内的商品列表
        for (int i = 0; i < detailsBinding.llFoodChoice.getChildCount(); i++) {
            ItemFoodBinding itemFoodBinding = (ItemFoodBinding) detailsBinding.llFoodChoice.getChildAt(i).getTag();
            int count = itemFoodBinding.getBeanFoodInfo().getSelectCount();
            if (count>0){
                PayLoad.FoodItem foodItem = new PayLoad.FoodItem();
                foodItem.setCount(count);
                foodItem.setWmFoodSkuId(itemFoodBinding.getBeanFoodInfo().getFoodSpuItem().getSkus().get(0).getId());
                foodItems.add(foodItem);
            }
        }
        wmOrderingList.setFoodList(foodItems);
        return payLoad;
    }

    public void listenerKeyEvent(KeyEvent event) {
        if (event.getAction() == KeyEvent.ACTION_DOWN) {
            if (selectView instanceof FrameLayout && selectView.getTag() instanceof ItemFoodBinding) {
                ItemFoodBinding itemFoodBinding = (ItemFoodBinding) selectView.getTag();
                switch (event.getKeyCode()) {
                    case KeyEvent.KEYCODE_0:
                        itemFoodBinding.getBeanFoodInfo().setSelectCount(0);
                        break;
                    case KeyEvent.KEYCODE_1:
                        itemFoodBinding.getBeanFoodInfo().setSelectCount(1);
                        break;
                    case KeyEvent.KEYCODE_2:
                        itemFoodBinding.getBeanFoodInfo().setSelectCount(2);
                        break;
                    case KeyEvent.KEYCODE_3:
                        itemFoodBinding.getBeanFoodInfo().setSelectCount(3);
                        break;
                    case KeyEvent.KEYCODE_4:
                        itemFoodBinding.getBeanFoodInfo().setSelectCount(4);
                        break;
                    case KeyEvent.KEYCODE_5:
                        itemFoodBinding.getBeanFoodInfo().setSelectCount(5);
                        break;
                    case KeyEvent.KEYCODE_6:
                        itemFoodBinding.getBeanFoodInfo().setSelectCount(6);
                        break;
                    case KeyEvent.KEYCODE_7:
                        itemFoodBinding.getBeanFoodInfo().setSelectCount(7);
                        break;
                    case KeyEvent.KEYCODE_8:
                        itemFoodBinding.getBeanFoodInfo().setSelectCount(8);
                        break;
                    case KeyEvent.KEYCODE_9:
                        itemFoodBinding.getBeanFoodInfo().setSelectCount(9);
                        break;
                }
                itemFoodBinding.setBeanFoodInfo(itemFoodBinding.getBeanFoodInfo());
                showTotals();
            }
        }
    }

    private void showTotals() {
        int numAll = 0;
        double priceAll = 0;
        for (int i = 0; i < detailsBinding.llFoodChoice.getChildCount(); i++) {
            ItemFoodBinding itemFoodBinding = (ItemFoodBinding) detailsBinding.llFoodChoice.getChildAt(i).getTag();
            numAll = numAll + itemFoodBinding.getBeanFoodInfo().getSelectCount();
            priceAll = priceAll + itemFoodBinding.getBeanFoodInfo().getSelectCount() *
                    itemFoodBinding.getBeanFoodInfo().getFoodSpuItem().getMinPrice();
        }
        String str = "已选择菜品 <font color='#FF0000'>" +
                numAll +
                "</font> 份    共计<font color='#FF0000'>￥" +
                priceAll +
                "</font> 元";
        detailsBinding.chooseTotals.setText(Html.fromHtml(str));
    }

    @Override
    public void onFocusChanged(View oldFocus, View newFocus) {
        selectView = newFocus;
        if (newFocus instanceof CheckBox) {
            int index = ViewUtil.getChildViewIndex(detailsBinding.llMenus, newFocus);
            if (index != selectTypeIndex) {
                selectTypeIndex = index;
                for (int i = 0; i < detailsBinding.llMenus.getChildCount(); i++) {
                    ((CheckBox) detailsBinding.llMenus.getChildAt(i)).setChecked(false);
                }
                ((CheckBox) newFocus).setChecked(true);
                addRightContent();
            }
        }
    }


}
